package ch.manage.movie.business;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class Manager {
	private List<Movie> movieList;

	static XStream xstream = new XStream(new DomDriver());
	private final File directoryPath = new File("I:/Spielfilme");
	private final static File XMLFilePath = new File("./XML/movieData.xml");

	@SuppressWarnings("unchecked")
	public List<Movie> loadMovies() {
		if (XMLFilePath.exists()) {
			// LOAD MOVIES FROM XML
			try{
				movieList = (List<Movie>) xstream.fromXML(XMLFilePath);
				String movieCoverPath;
				for(Movie movie:movieList){
					movieCoverPath= movie.getCoverImagePath();
					movie.setCover(ImageIO.read(new File(movieCoverPath)));
				}
			}catch (Exception e) {
				XMLFilePath.delete();
				movieList = loadMovies();
			}
		} else {
			// LOAD MOVIES FROM DIR
			movieList = MovieScanner.scan(directoryPath);
			saveToFile(movieList);
			return movieList;
		}
		return movieList;

	}

	public static void saveToFile(List<Movie> movieList) {
		String movieListXML = xstream.toXML(movieList);
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(XMLFilePath));
			bw.write(movieListXML);
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
